package com.hospital.register.sms.controller;

import com.hospital.register.common.constants.redis.UserRedisConstants;
import com.hospital.register.common.result.Result;
import com.hospital.register.constants.RegexConstants;
import com.hospital.register.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Api(tags = "短信相关请求")
@RestController
@RequestMapping("/api/sms")
@Validated
public class SmsController {

    /**
     * 处理短信业务
     */
    @Autowired
    private SmsService smsService;

    /**
     * 访问 Redis
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送短信验证码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "path", dataTypeClass = String.class,required = true)
    })
    @GetMapping("/send/{phone}")
    public Result sendCode(
            @PathVariable @NotNull(message = "手机号不可为空") @Pattern(regexp = RegexConstants.PHONE, message = "必须是11位手机号") String phone) {
        String sentVerificationCode = this.redisTemplate.opsForValue().get(UserRedisConstants.LOGIN_VERIFICATION_CODE + phone);

        if (!StringUtils.isEmpty(sentVerificationCode)) {
            Result<Object> result = Result.fail();
            result.setMessage("不可重复发送");
            return result;
        }

        boolean isSent = this.smsService.sendVerificationCode(phone);

        if (isSent) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

}
